package org.hscoder.springboot.security;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder().username("lilei").password(passwordEncoder().encode("111111")).
                roles("USER").build();
        UserDetails UserAdmin = User.builder().username("admin").password(passwordEncoder().encode("111111")).
                roles("ADMIN").build();
        return new InMemoryUserDetailsManager(user, UserAdmin);
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                //静态资源处理
                .antMatchers("/", "/static").permitAll()
                //需要验证的url
                .antMatchers("/user", "/user/**").authenticated()
                //需要验证及相应权限的url
                .antMatchers("/admin").hasRole("ADMIN")
                .and()
                //使用表单登录
                .formLogin()
                //登录成功跳转的URL
                .defaultSuccessUrl("/user")
                //登录页面URL
                .loginPage("/login").permitAll()
                .and()
                .logout().permitAll();

    }

}